﻿
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Vav.Data.Utils;

namespace Vav.Api
{
    public class GlobalException
    {
        private static Logger log = LogManager.GetLogger("logger");

        public static void ExceptionHandler(IApplicationBuilder errApp)
        {
            errApp.Run(async context =>
            {
                var feature = context.Features.Get<IExceptionHandlerFeature>();
                context.Response.StatusCode = 200;
                context.Response.ContentType = "application/json; charset=utf-8";
                switch (feature?.Error)
                {

                    case HttpRequestException ex:
                        log.Error(ex);
                        await context.Response.WriteAsync(new ApiBaseModel { msg = ex.Message, status = false, result = null }.ToJson());
                        break;
                    case Exception ex:
                        log.Error(ex);
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync(new ApiBaseModel { msg = ex.Message, status = false, result = null }.ToJson());
                        break;
                    default:
                        context.Response.StatusCode = 500;
                        await context.Response.WriteAsync(new ApiBaseModel { msg = "unknown exception.", status = false, result = null }.ToJson());
                        break;
                }
            });
        }
    }
}
